package com.rjpacket.supernews.app.utils;

import java.io.*;

/**
 * Created by aaa on 15-3-11.
 */
public class StreamUtil {

    /**
     * 工具类不要实例化
     */
    private StreamUtil() {

    }

    /**
     * 所有流的关闭都可以调用这个方法
     *
     * @param stream
     */
    public static void close(Object stream) {
        if (stream != null) {
            try {
                if (stream instanceof InputStream) {
                    ((InputStream) stream).close();
                } else if (stream instanceof OutputStream) {
                    ((OutputStream) stream).close();
                } else if (stream instanceof Reader) {
                    ((Reader) stream).close();
                } else if (stream instanceof Writer) {
                    ((Writer) stream).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 从输入流读到输出流里，返回读的字节数
     *
     * @param in
     * @param out
     * @return
     * @throws IOException
     */
    public static long readStream(InputStream in, OutputStream out) throws IOException {
        long ret = 0;
        if (in != null && out != null) {
            byte[] buf = new byte[128];
            int len;
            while (true) {
                len = in.read(buf);
                if (len == -1) {
                    break;
                }
                ret += len;
                out.write(buf, 0, len);
            }
            buf = null;
        }
        return ret;
    }

    /**
     * 从流里读出字节数组
     *
     * @param in
     * @return
     * @throws IOException
     */
    public static byte[] readStream(InputStream in) throws IOException {
        byte[] ret = null;
        if (in != null) {
            ByteArrayOutputStream bout = null;

            bout = new ByteArrayOutputStream();

            readStream(in, bout);

            ret = bout.toByteArray();

            close(bout);

            bout = null;
        }
        return ret;
    }
}
